import { LocationQueryRaw, RouteLocationRaw, RouteParamsRaw, useRouter } from "vue-router";

interface OpenOptions {
  name?: string;
  fullPath?: string;
  query?: LocationQueryRaw;
  params?: RouteParamsRaw;
  hash?: string;
}

export function useJumper() {
  const router = useRouter();

  return {
    open: (options: OpenOptions) => {
      // 在新标签页打开 fullPath
      if (options.fullPath) {
        window.open(`${options.fullPath}`, "_blank");
        return;
      }

      // 在新标签页打开 route
      const { query = {}, params = {} } = options;
      const route = router.resolve({
        name: options.name,
        query,
        params,
      });
      if (options.hash) route.hash = "#" + options.hash;
      const goRoute = route.href + route.hash;
      window.open(`${goRoute}`, "_blank");
    },
    push: (to: RouteLocationRaw) => {
      router.push(to);
    },
    replace: (to: RouteLocationRaw) => {
      router.replace(to);
    },
    back: () => {
      router.back();
    },
    forward: () => {
      router.forward();
    },
    go: (delta: number) => {
      router.go(delta);
    },
  };
}
